package com.github.hwangrq.springboothomework.boot.init;

import com.github.hwangrq.springboothomework.boot.config.AppConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;

/**
 * @author: hwangrq
 * @date: 2021/3/3 14:38
 * @description: 基于Servlet3.0的，相当于以前<b>web.xml</b>配置文件的配置类
 */
public class MyServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses,
                          ServletContext servletContext) throws ServletException {
        servletContext.log("Tomcat 启动过程中注册自己的servlet...");
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //注册spring的配置类（替代传统项目中xml的configuration）
        ac.register(AppConfig.class);
        ac.refresh();

        //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/*");
        servletContext.log("Tomcat 的servlet注册完毕...");

    }
}
